import base64
import pickle

from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request,user,response):

    # 合并购物车，获取cookie中的数据并写入redis
    cookie_data = request.COOKIES.get('carts')

    if not cookie_data:

        return response

   # 解密

    carts_dict = pickle.loads(base64.b16decode(cookie_data))

    new_dict = {}

    new_add = []

    new_rem = []

    for sku_id,items in carts_dict.items():

        new_dict[sku_id]=items['count']

        if items['selected']:

            new_add.append(sku_id)
        else:

            new_rem.append(sku_id)

    # 将新的字典数据写入到redis
    redis_conn = get_redis_connection('carts')

    pl = redis_conn.pipeline()

    # 将new_dict写入hash中
    pl.hmset('carts_%s'%request.user.id,new_dict)

    # 将勾选状态更新到redis
    if new_add:

        pl.sadd('selected_%s'%request.user.id,*new_add)

    if new_rem:

        pl.srem('selected_%s'%request.user.id,*new_rem)

    pl.execute()

    response.delete_cookie('carts')

    return response



# def merge_cart_cookie_to_redis(request, user, response):
#
#     # 登录后合并cookie购物车数据到Redis
#
#     # 获取cookie中的购物车数据
#     cookie_cart = request.COOKIES.get('carts')
#     # cookie中没有数据就响应结果
#     if not cookie_cart:
#         return response
#     cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
#
#     new_dict = {}
#     new_add = []
#     new_remove = []
#     # 同步cookie中购物车数据
#     for sku_id, item in cart_dict.items():
#         new_dict[sku_id] = item['count']
#
#         if item['selected']:
#             new_add.append(sku_id)
#         else:
#             new_remove.append(sku_id)
#
#     # 将new_cart_dict写入到Redis数据库
#     redis_conn = get_redis_connection('carts')
#     pl = redis_conn.pipeline()
#     pl.hmset('carts_%s' % user.id, new_dict)
#     # 将勾选状态同步到Redis数据库
#     if new_add:
#         pl.sadd('selected_%s' % user.id, *new_add)
#     if new_remove:
#         pl.srem('selected_%s' % user.id, *new_remove)
#     pl.execute()
#
#     # 清除cookie
#     response.delete_cookie('carts')
#
#     return response